package com.fenghongzhang.day019;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 音乐播放的服务
 */
public class MusicService extends Service {

    private MyBroadcastReceiver myBroadcastReceiver;
    //缓存数据中的下标
    private int index = 0;

    private int sPlayModel =0;
    private static final String TAG = "MusicService";
    //播放音乐
    private MediaPlayer mediaPlayer ;
    private List<Song> list;

    private boolean isNext = true;

    private Timer timer;

    public MusicService() {

    }

    //1次
    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        //sd 授权还没有拿到
        list =  MusicUtil.getMusic(this);

        //3, 动态注册一下,广播接收者
         myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.feng.pause");
        intentFilter.addAction("com.feng.restart");
        registerReceiver(myBroadcastReceiver,intentFilter);

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                sendNotify();
            }
        },0,1000);

    }


    //2, 创建内部的广播接收者.
    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals("com.feng.pause")){
                pause();
            }else if (action.equals("com.feng.restart")){
                restart();
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //为了没有页码的时候,也可以操作音乐 . 发送前台服务

        sendNotify();

        return super.onStartCommand(intent, flags, startId);
    }

    private void sendNotify() {
        Notification.Builder builder = new Notification.Builder(this);

        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentTitle("biaoto");

        //自定义一个通知布局. 里面有btn可以点击
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify_layout);

        //改标题
        remoteViews.setTextViewText(R.id.notify_title,list.get(index).getTitle());

        //进度条
        remoteViews.setProgressBar(R.id.notify_bar,
                Integer.parseInt(list.get(index).getDuration()),
                mediaPlayer.getCurrentPosition(),false);

        //1 首先给按钮添加一个点击事件
        Intent intent1 = new Intent();
        intent1.setAction("com.feng.pause");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, intent1, 0);
        //点击事件
        remoteViews.setOnClickPendingIntent(R.id.notify_pause,broadcast);


        //暂停
        Intent intent2 = new Intent();
        intent2.setAction("com.feng.restart");
        PendingIntent broadcast1 = PendingIntent.getBroadcast(this, 0, intent2, 0);
        remoteViews.setOnClickPendingIntent(R.id.notify_restart,broadcast1);


        //点击事件
        remoteViews.setOnClickPendingIntent(R.id.notify_pause,broadcast);


        builder.setCustomContentView(remoteViews);//24
//        builder.setContent() //22


        //发送前台服务
        startForeground(1,builder.build());
    }

    class MyBinder extends Binder{
//        public void callPlay(){
////            play();
////        }
////        public void callNext(){
////            next();
////        }

        public MusicService getService(){
            return MusicService.this;
        }
    }

    //start bind  unbind
    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        stopForeground(true);
        mediaPlayer.release();
        unregisterReceiver(myBroadcastReceiver);
    }

    @Override
    public IBinder onBind(Intent intent) {
       return new MyBinder();
    }

    public void play(int position){
        index = position;
        sendNotify();
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource("http://music.163.com/song/media/outer/url?id=346573.mp3");
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });
            //播放完成以后怎么办
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //播放模式
                    playModel();
                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.i(TAG, "onError: ");
                    next();
                    return false;
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void playModel() {
        /**
         * 根据播放模式改一个下标而已
         */
        if(sPlayModel == MusicUtil.ORDER){
            //下一首,或者上一首的代码
            if(isNext){
                if(++index > list.size()-1){
                    index = 0;
                }
            }else{
                if(--index < 0){
                    index = 0;
                }
            }
        }else if (sPlayModel == MusicUtil.RANDOM) {
            index = new Random().nextInt(list.size());
        }else if(sPlayModel ==  MusicUtil.SINGEL){

        }
        play(index);
    }


    public void pause(){
        mediaPlayer.pause();
    }
    public void stop(){
        mediaPlayer.stop();
    }

    public void restart(){
        mediaPlayer.start();

    }

//
//    public void set1(){
//        mediaPlayer.setLooping(false);
//    }

    //设置播放模式
    public void setPlayModel(int model){
        sPlayModel = model;
    }

    public int getSeekBarMax(){
        return Integer.parseInt(list.get(index).getDuration());
    }

    public int getProgress(){
        return mediaPlayer.getCurrentPosition();
    }

    //改变进度
    public void setProgress(int progress){
        mediaPlayer.seekTo(progress);
    }

    public void next(){


//        if(++index > list.size()-1){
//            index = 0;
//        }
//        play(index);

        isNext = true;
        playModel();


    }
    public void pre(){
//        if(--index < 0){
//            index = 0;
//        }
//        play(index);

        isNext = false;
        playModel();
    }



}
